package cn.gpdi.framework.util;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

/**
 * 文件对象操作
 * Created by 司徒鑫(QQ:156845600) on 2018/8/1.
 */
public class FileUtil {
    /**
     * 文件上传，获取请求中的文件
     * @param request
     * @return List<MultipartFile>
     */
    public static List<MultipartFile> getMultipartFile(HttpServletRequest request){
        List<MultipartFile> fileList=new ArrayList<MultipartFile>();
        CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(request.getSession().getServletContext());
        //检查form中是否有enctype="multipart/form-data"
        if(multipartResolver.isMultipart(request))
        {
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
            //获取multiRequest 中所有的文件名
            Iterator iter=multiRequest.getFileNames();
            while(iter.hasNext())
            {
                String fn=iter.next().toString();
                //一次遍历所有文件
                List<MultipartFile> files=multiRequest.getFiles(fn);
                fileList.addAll(files);
            }
        }
        return fileList;
    }
}
